﻿using System; using HISModels.ViewModel;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using KeanuMvc.Reference;
using HIS.Utils;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using HISModels.Entities;
using System.Configuration;

namespace HIS.Controllers.Admins {

    public class Role : HIS.Controllers.AppBaseController {

        #region Fields
        private string strAction = string.Empty;
        private string strNotification = string.Empty;
        string paramActionNull = string.Empty; 
        private SysRole sysRole = null;
        private SysRoleAction sysRoleAction = null;

        #endregion

        #region Role
        public Role() {
            Data.Add("Pagetitle", "Roles");
            Data.Add("Notification", strNotification);
        }

        [HIS.Utils.Securities.Authorization(RoleAction = "sys-role")]
        public override void Index() {
            try {
                string ddlLocation = DropDownRoleLocation("");
                Data.Add("ddlLocation", ddlLocation);

                RenderFile("admins\\roles\\role.html");
            } catch (Exception ex) {
                HttpContext.Current.Response.Write(ex.Message);
            }
        }

        [HIS.Utils.Securities.Authorization(RoleAction = "sys-role")]
        public void TableList() {
            try {
                string rolename = HttpContext.Current.Request["rolename"].NullSafeToString();
                int location = Convert.ToInt32(HttpContext.Current.Request["location"].NullSafeToString());
                string ssearch = "rolename=" + rolename + ";location=" + location;

                PostDataTablesNet pagingSearch = new PostDataTablesNet();
                pagingSearch.iDisplayLength = Convert.ToInt32(HttpContext.Current.Request["iDisplayLength"]);
                pagingSearch.iDisplayStart = Convert.ToInt32(HttpContext.Current.Request["iDisplayStart"]);
                pagingSearch.sEcho = Convert.ToInt32(HttpContext.Current.Request["sEcho"]);
                pagingSearch.sSearch = ssearch;

                //string strUri = Data["servicerooturl"] + "sys/roles/paging/?format=json";
                string strUri = Global.ServiceUriDictionary["rolepaging"] + Global.ServiceUriDictionary["requestformat"];
                StringReader stringReader = base.RestService.PostJson(strUri, JsonConvert.SerializeObject(pagingSearch));
                string strJson = stringReader.ReadToEnd();
                stringReader.Dispose();
                base.RestService.Dispose();
                HttpContext.Current.Response.Write(strJson);
            } catch (Exception ex) {
                HttpContext.Current.Response.Write(ex.Message);
            }
        }

        [HIS.Utils.Securities.Authorization(RoleAction = "sys-role")]
        public void EditRole() {
            StringReader stringReader = null;
            int roleid = 0;
            try {
                roleid = Convert.ToInt32(HttpContext.Current.Request["id"]);
            } catch {
                GoToUrl("role/");
                return;
            }

            try {
                //string strUri = Data["servicerooturl"] + "sys/roles/" + roleid + "?format=json";
                string strUri = Global.ServiceUriDictionary["role"] + roleid + Global.ServiceUriDictionary["requestformat"];
                stringReader = base.RestService.GetJson(strUri);
                sysRole = JsonConvert.DeserializeObject<SysRole>(stringReader.ReadToEnd());
                Data.Add("ddlLocationAE", DropDownLocation(sysRole.HospitalUnitId.NullSafeToString()));
                if (sysRole.DefaultUrl == null) {
                    sysRole.DefaultUrl = "";
                }
                Data.Add("sysRole", sysRole);
                Data.Add("IsCreate", "false");
                Data.Add("Actionform", Data["rooturl"] + "admins/role/editrole/?id=" + roleid);
                Data["Pagetitle"] += " :: Edit role";
                Data["Notification"] = strNotification;
            } catch (Exception ex) {
                Data["Notification"] = Helper.ErrorMessage(ex.Message);
            } finally {
                RenderFile("Admins\\Roles\\editrole.html");
                if (stringReader != null) stringReader.Dispose();
                base.RestService.Dispose();
            }
        }

        [HIS.Utils.Securities.Authorization(RoleAction = "sys-role")]
        public void CreateRole() {
            StringReader stringReader = null;
            try {
                Data["Pagetitle"] += " :: Add Role";
                sysRole = new HISModels.Entities.SysRole();
                sysRole.DescValue = "";
                sysRole.DefaultUrl = "";
                Data.Add("ddlLocationAE", DropDownLocation(""));
                Data.Add("sysRole", sysRole);
                Data.Add("IsCreate", "true");
                Data.Add("Actionform", Data["rooturl"] + "admins/role/createrole/");
                Data["Notification"] = strNotification;

            } catch (Exception ex) {
                Data["Notification"] = Helper.ErrorMessage(ex.Message);
            } finally {
                RenderFile("Admins\\Roles\\editrole.html");
                if (stringReader != null) stringReader.Dispose();
                base.RestService.Dispose();
            }
        }

        [HIS.Utils.Securities.Authorization(RoleAction = "sys-role")]
        public void DeleteRole() {
            StringReader stringReader = null;
            int id = 0;
            try {
                id = Convert.ToInt32(HttpContext.Current.Request["id"]);
            } catch {
                GoToUrl("role/");
                return;
            }

            try {
                sysRole = new HISModels.Entities.SysRole();
                //string strUri = Data["servicerooturl"] + "sys/Roles/?format=json";
                string strUri = Global.ServiceUriDictionary["role"] + Global.ServiceUriDictionary["requestformat"];
                stringReader = base.RestService.DeleteJson(strUri, JsonConvert.SerializeObject(id));
                strNotification = JsonConvert.DeserializeObject<string>(stringReader.ReadToEnd());
                if (strNotification == string.Empty) strNotification = Helper.SuccessMessage("Data has been successfully deleted!");
                Data["Notification"] = strNotification;

            } catch (Exception ex) {
                Data["Notification"] = Helper.ErrorMessage(ex.Message);
            } finally {
                //RenderFile("Admins\\Actions\\editactiongroup.html");
                //stringReader.Dispose();
                //base.RestService.Dispose();


                HttpContext.Current.Response.Redirect(Data["rooturl"] + "admins/role/");

                //GoToUrl("actiongroup/");

                base.RestService.Dispose();
            }
        }

        public string DropDownRoleLocation(string Selected) {
            StringReader stringReaderDropDown = null;
            string strResult = string.Empty;
            string Name = string.Empty;
            string strUri = "";
            strUri = Global.ServiceUriDictionary["hospital"] + Global.ServiceUriDictionary["requestformat"];
            try {
                stringReaderDropDown = base.RestService.GetJson(strUri);
                List<HISModels.Entities.RefHu> listSp = JsonConvert.DeserializeObject<List<RefHu>>(stringReaderDropDown.ReadToEnd());
                List<object[]> activeArr = new List<object[]>();

                activeArr.Add(new object[] { -1, Name = "- All Location -" });

                foreach (RefHu item in listSp) activeArr.Add(new object[] { item.Id, Name = item.NameValue });

                strResult = KeanuMvc.Reference.Html.DropDown("location", string.Empty, activeArr, Selected);
                activeArr.Clear();
                activeArr = null;
            } catch {
            } finally {
                // stringReaderDropDown.Dispose();
            }
            return strResult;
        }

        public string DropDownLocation(string Selected) {
            StringReader stringReaderDropDown = null;
            string strResult = string.Empty;
            //string strUri = Data["servicerooturl"] + "sys/roles/?format=json";
            string strUri = Global.ServiceUriDictionary["hospital"] + Global.ServiceUriDictionary["requestformat"];
            try {
                stringReaderDropDown = base.RestService.GetJson(strUri);
                List<RefHu> listHu = JsonConvert.DeserializeObject<List<RefHu>>(stringReaderDropDown.ReadToEnd());
                List<object[]> activeArr = new List<object[]>();
                //activeArr.Add(new object[] { "-1", "--Select--" });
                foreach (RefHu item in listHu) activeArr.Add(new object[] { item.Id, item.NameValue });
                strResult = KeanuMvc.Reference.Html.DropDown("HospitalUnitId", string.Empty, activeArr, Selected);
                activeArr.Clear();
                activeArr = null;
            } catch {
            } finally {
                stringReaderDropDown.Dispose();
            }
            return strResult;
        }

        [HIS.Utils.Securities.Authorization(RoleAction = "sys-role")]
        public void SaveRolesToService() {
            StringReader stringReader = null;
            string strUri = string.Empty;
            try {

                sysRole = new SysRole(); Utils.Helper.SetNullToEmptyString(sysRole);
                if (HttpContext.Current.Request["IsCreate"] != "true") {
                    int id = 0;
                    try {
                        id = Convert.ToInt32(HttpContext.Current.Request["id"]);
                    } catch { }
                    strUri = Global.ServiceUriDictionary["role"] + id + Global.ServiceUriDictionary["requestformat"];
                    ///Get Rest///
                    stringReader = base.RestService.GetJson(strUri);
                    sysRole = JsonConvert.DeserializeObject<SysRole>(stringReader.ReadToEnd());
                }

                sysRole.PostHandler<HISModels.Entities.SysRole>();
                sysRole.DescValue = sysRole.DescValue.ReplaceSpecialChar("-").ToLower();
                strUri = Global.ServiceUriDictionary["role"] + Global.ServiceUriDictionary["requestformat"];

                if (HttpContext.Current.Request["IsCreate"] == "true") {
                    stringReader = base.RestService.PostJson(strUri, JsonConvert.SerializeObject(sysRole));
                } else {
                    stringReader = base.RestService.PutJson(strUri, JsonConvert.SerializeObject(sysRole));
                }


                sysRole = JsonConvert.DeserializeObject<SysRole>(stringReader.ReadToEnd());

                if (sysRole != null) {
                    strNotification = Helper.SuccessMessage(base.RestService.ObjectResponse.Headers[HISModels.Enums.ResponseMessage.DetailHeadesMessageKey].ToString());
                } else {
                    strNotification = Helper.ErrorMessage(base.RestService.ObjectResponse.Headers[HISModels.Enums.ResponseMessage.DetailHeadesMessageKey].ToString());
                }


                strNotification = "{\"strNotification\": \"" + strNotification + "\"}";
                HttpContext.Current.Response.Write(strNotification);

            } catch (Exception ex) {
                strNotification = ex.Message;
            } finally {

                base.RestService.Dispose();
            }
        }
        #endregion

        #region roleaction
        public string DropDownGroup() {
            StringReader stringReaderDropDown = null;
            string strResult = string.Empty;
            //string strUri = Data["servicerooturl"] + "sys/roleactions/actiongroup/?format=json";
            string strUri = Global.ServiceUriDictionary["actgroups"] + Global.ServiceUriDictionary["requestformat"];
            try {
                stringReaderDropDown = base.RestService.GetJson(strUri);
                List<SysActionGroup> listGroupAction = JsonConvert.DeserializeObject<List<SysActionGroup>>(stringReaderDropDown.ReadToEnd());
                List<object[]> activeArr = new List<object[]>();

                foreach (SysActionGroup item in listGroupAction) activeArr.Add(new object[] { item.Id, item.DescValue });

                strResult = KeanuMvc.Reference.Html.DropDown("actiongroup", string.Empty, activeArr, "");
                activeArr.Clear();
                activeArr = null;
            } catch {
            } finally {
                stringReaderDropDown.Dispose();
            }
            return strResult;
        }

        [HIS.Utils.Securities.Authorization(RoleAction = "sys-role")]
        public void tryJson() {
            int roleid = 0;
            int groupid = 0;

            groupid = Convert.ToInt32(HttpContext.Current.Request["groupid"]);
            roleid = Convert.ToInt32(HttpContext.Current.Request["roleid"]);

            //string strUri = Data["servicerooturl"] + "sys/actiongroups/" + groupid +  "/" + roleid + "?format=json";
            //stringReader = base.RestService.GetJson(strUri);


            var x = new { id = 1, name = "abc" };
            string oo = JsonConvert.SerializeObject(x);
            HttpContext.Current.Response.Write(oo);


        }

        [HIS.Utils.Securities.Authorization(RoleAction = "sys-role")]
        public void SetRoleActions() {
            /// Get id of role
            int roleid = 0;

            try {
                roleid = Convert.ToInt32(HttpContext.Current.Request["id"]);

                Data.Add("roleid", roleid);

            } catch {
                GoToUrl("role/");
                return;
            }
            StringReader stringReader = null;
            try {
                /// Set url to invoke
                //string strUri = Data["servicerooturl"] + "sys/actiongroups/1/" + roleid + "?format=json";
                string strUri = Global.ServiceUriDictionary["actgroups"] + "1/" + roleid + Global.ServiceUriDictionary["requestformat"];
                stringReader = base.RestService.GetJson(strUri);
                /// Set json to list object
                var detail = new[] {
                    new { Id = 0, DescValue = string.Empty, RoleID = 0 }
                };
                var o = new { Header = new SysRole(), detail };
                string json = stringReader.ReadToEnd();
                var roleAction = JsonConvert.DeserializeAnonymousType(json, o);

                /// Set object to render
                Data.Add("ddActionGroup", DropDownGroup());
                Data.Add("sysRole", roleAction.Header);
                Data.Add("roleAction", roleAction.detail);
                Data["Pagetitle"] += " :: Setting role action (" + roleAction.Header.DescValue + ")";

            } catch (Exception ex) {
                HttpContext.Current.Response.Write(ex.Message);
            } finally {
                RenderFile("Admins\\Roles\\editactioninrole.html");
                if (stringReader != null) stringReader.Dispose();
            }
        }

        [HIS.Utils.Securities.Authorization(RoleAction = "sys-role")]
        public void ActionList() {
            int roleid = 0;
            int groupid = 0;
            try {
                roleid = Convert.ToInt32(HttpContext.Current.Request["roleid"]);
                groupid = Convert.ToInt32(HttpContext.Current.Request["groupid"]);
            } catch { }
            StringReader stringReader = null;
            try {
                /// Set url to invoke
                string strUri = Global.ServiceUriDictionary["actgroups"] + groupid + "/" + roleid + Global.ServiceUriDictionary["requestformat"];
                stringReader = base.RestService.GetJson(strUri);
                /// Set json to list object
                var detail = new[] {
                    new { Id = 0, DescValue = string.Empty, RoleId = 0 }
                };
                var o = new { Header = new SysRole(), detail };
                string json = stringReader.ReadToEnd();
                var roleAction = JsonConvert.DeserializeAnonymousType(json, o);
                Data.Add("roleAction", roleAction.detail);

                string strHtml = string.Empty;

                foreach (var item in roleAction.detail) {
                    strHtml += "<tr>";
                    strHtml += "<td>";
                    if (item.RoleId == 0) {
                        strHtml += "<input type=\"checkbox\" name=\"valueaction\"  value=\"" + item.Id + "\"/>";
                    } else {
                        strHtml += "<input type=\"checkbox\" name=\"valueaction\"  value=\"" + item.Id + "\" checked=\"checked\" />";
                    }
                    strHtml += "</td>";
                    strHtml += "<td>" + item.DescValue + "</td>";
                    strHtml += "</tr>";
                }
                HttpContext.Current.Response.Write(strHtml);
            } catch (Exception ex) {
                HttpContext.Current.Response.Write(ex.Message);
            } finally {

                if (stringReader != null) stringReader.Dispose();
            }
        }

        [HIS.Utils.Securities.Authorization(RoleAction = "sys-role")]
        public void SaveRolesAcrtionToService() {
            StringReader stringReader = null;
            string strUri = string.Empty;
            
            try {
                //string paramActionNull; 
                sysRoleAction = new SysRoleAction(); Utils.Helper.SetNullToEmptyString(sysRoleAction);
                List<SysRoleAction> listAction = new List<SysRoleAction>();
                int roleid = Convert.ToInt32(HttpContext.Current.Request["roleid"]);

                string[] param = HttpContext.Current.Request.Params.ToString().Split('&');
                string temp = HttpContext.Current.Request["valueaction"];
                for (int i = 0; i < param.Length; i++) {
                    if (param[i].Contains("valueaction")) {
                        string value = param[i].Split('=')[1];
                        SysRoleAction newAction = new SysRoleAction();
                        newAction.ActionId = Convert.ToInt32(value);
                        newAction.RoleId = roleid;
                        listAction.Add(newAction);  
                    }       
                }

                if (temp == null) {
                    var ddl = HttpContext.Current.Request["actiongroup"];
                    paramActionNull = "groupid=" + ddl + ";roleid=" + roleid;

                    strUri = Global.ServiceUriDictionary["actgroupsrole"] + Global.ServiceUriDictionary["requestformat"];
                    stringReader = base.RestService.DeleteJson(strUri, JsonConvert.SerializeObject(paramActionNull));
                    string strNotification = JsonConvert.DeserializeObject<string>(stringReader.ReadToEnd());
                    
                } else {
                    strUri = Global.ServiceUriDictionary["actgroupsrole"] + Global.ServiceUriDictionary["requestformat"];
                    stringReader = base.RestService.PostJson(strUri, JsonConvert.SerializeObject(listAction));
                    listAction = JsonConvert.DeserializeObject<List<SysRoleAction>>(stringReader.ReadToEnd());
                }

                

                if (sysRoleAction != null) {
                    strNotification = Helper.SuccessMessage(base.RestService.ObjectResponse.Headers[HISModels.Enums.ResponseMessage.DetailHeadesMessageKey].ToString());
                } else {
                    strNotification = Helper.ErrorMessage(base.RestService.ObjectResponse.Headers[HISModels.Enums.ResponseMessage.DetailHeadesMessageKey].ToString());
                }

                // insert action name into File text
                try {
                    strUri = Global.ServiceUriDictionary["roleactrole"] + roleid + Global.ServiceUriDictionary["requestformat"];
                    stringReader = base.RestService.GetJson(strUri);
                    var b = new[] {
                    new { roleid = 0, actionname = string.Empty } };
                    var a = JsonConvert.DeserializeAnonymousType(stringReader.ReadToEnd(), b);

                    string fileLoc = HttpContext.Current.Request.PhysicalApplicationPath + "Cache\\RoleAction\\" + roleid + ".txt";

                    FileStream fs = null;

                    if (File.Exists(fileLoc)) {
                        File.Delete(fileLoc);
                    } else {
                        using (fs = File.Create(fileLoc)) {
                            fs.Dispose();
                        }
                    }

                    using (StreamWriter sw = new StreamWriter(fileLoc)) {
                        foreach (var item in a) {
                            string value = item.actionname;
                            sw.WriteLine(value);
                        }

                        sw.Dispose();
                    }
                } catch { }

                strNotification = "{\"strNotification\": \"" + strNotification + "\"}";
                HttpContext.Current.Response.Write(strNotification);

            } catch (Exception ex) {
                strNotification = ex.Message;
            } finally {

                base.RestService.Dispose();
            }
        }
        #endregion

    }
}